/// faichou  2017-01-03
var app = getApp()
var util=require('../../utils/util')
var dialog=require('../../utils/dialog')
const RECEIVE_INFO = 'receiveInfo'
var req=require('./addressReq.js')

const ADDRESS_MAIN = 'addressMain';
const API = 'https://source.magicmanufactory.com/xiaochegnxu/json/addresschina-city-area-zip.min.json'

Page({
    data:{
        receiverName: '', // 用户名
        receiverPhone: '', // 手机号
        receiverYZ: '', // 邮政编码
        detailAddr:'', // 详细地址
        addressId: '', // id
        province: '', // 省
        city: '', // 市
        suburb: '', // 区
        justAdd: true, // 添加地址还是编辑地址flag

        arrayProvince: ['省'], // 省
        indexProvince: 0, // index省
        arrayCity: ['市'], // 市
        arrayDotCity: ['市'], // 显示的市，太长用...结尾
        indexCity: 0, // index市
        arrayDistrict: ['区县'], // 区县
        arrayDotDistrict: ['区县'], // 显示的区县，太长用...结尾
        indexDistrict: 0, // index区县
        addressMain: [], // 总数据。1.从网络请求 2.从本地加载
        isChangeCity: false, // 检验编辑地址时是否改过省市区
    },
    // 给长度太长的地址名截断，添加...尾巴
  addDot: function (arr) {
    if (arr instanceof Array) {
      return arr.map(val => {
        // 最长显示四个汉字
        if (val.length > 4) {
          val = val.slice(0, 4) + '...';
          return val;
        } else {
          return val;
        }
      })
    }
  },
  // 本打算给province用，结果city也用了，函数里的参数没来得及改名
  // 由于API获取的省市区名字可能不和原有的名字一致，例如“内蒙古”vs“内蒙古自治区”，所以用前两个字来判断index
  // 编辑地址后，从已有地址找到API数据里的index
  findIndexOfDefault: function(provinceArray, province) {
      let index = 0;
      let provinceShortName = '';
      if (province.length === 2) {
         provinceShortName = province
      } else {
         provinceShortName = province[0] + province[1]
      }
      index = provinceArray.findIndex(function(element, index){
         let exactName = element[0] + element[1]
         return exactName === provinceShortName;
      })
      return index;
  },
  // 从API请求地址，这里请求完要注意设置index
  requestAddress: function(option) {
    var that = this
    
    wx.request({
      //必需
      url: API,
      method: 'GET',
      header: {
          'Content-Type': 'application/json'
      },
      success: function(res) {
          let allProvince = []
          // 遍历所有数据，将name代表的province放到数组里
          res.data.forEach(function(element){
              allProvince.push(element.name)
          })
          // 如果是编辑地址来的，找到index
          if (option.justAdd === '0') {
              let receiveInfo = app.globalData.receiveInfo
              let index = that.findIndexOfDefault(allProvince, receiveInfo.province)
              that.setData({
                  indexProvince: index,
              })
          }
          
          that.setData({
              arrayProvince: allProvince,
              addressMain: res.data,
          })
          // 存储到localStorage
          wx.setStorage({
              key: ADDRESS_MAIN,
              data: res.data
          })
      },
      fail: function(res) {
          
      },
      complete: function(res) {
      }
    })
  },
  // 在onLoad时候加载数据，有个弊端，不能用toast
  onLoad: function(option){
    var that = this
    /// 如果只是添加地址，而且用户恰好是北京-北京-东城区，那么用户应该不会选择
    // so 设置上province，city，suburb
    if (option.justAdd === '1') {
      that.setData({
          justAdd: true,
          province: '北京',
          city: '北京',
          suburb: '东城区',
      })
    }else{
      /// 如果是编辑地址，得获取到所有数据，因为push不能传递Object，所以把数据放在了app.globalData里
      // 注意这里将arrayProvince, arrayDotCity, arrayDotDistrict也要设置上
      let receiveInfo = app.globalData.receiveInfo
      if (receiveInfo) {
          that.setData({
              receiverName: receiveInfo.receiver,
              receiverPhone: receiveInfo.phoneNo,
              receiverYZ: receiveInfo.postal,
              detailAddr: receiveInfo.detail,
              addressId: receiveInfo.addressId,
              province: receiveInfo.province,
              city: receiveInfo.city,
              suburb: receiveInfo.suburb,
              justAdd: false,
              arrayProvince: [receiveInfo.province],
              arrayDotCity: [receiveInfo.city],
              arrayDotDistrict: [receiveInfo.suburb],
          })
      }
    }
    /// 从localStorage里取数据
    wx.getStorage({
      key: ADDRESS_MAIN,
      success: function(res){
          let allProvince = []
          res.data.forEach(function(element){
              allProvince.push(element.name)
          })
          // 修改地址，需要将all省，已选中省的所有市，已选中市的所有区要存下，而且还要找出index
          if (option.justAdd === '0') {
              let receiveInfo = app.globalData.receiveInfo
              let indexP = that.findIndexOfDefault(allProvince, receiveInfo.province)
              let allCity = []
              res.data[indexP].child.forEach(function(element){
                allCity.push(element.name)
              })
              let dotCity = that.addDot(allCity)
              let indexC = that.findIndexOfDefault(allCity, receiveInfo.city)
              let allDistrict = []
              res.data[indexP].child[indexC].child.forEach(function(element){
                allDistrict.push(element.name)
              })
              let dotDistrict = that.addDot(allDistrict)
              let indexD = that.findIndexOfDefault(allDistrict, receiveInfo.suburb)
      that.setData({
          indexProvince: indexP,
          indexCity: indexC,
          indexDistrict: indexD,
          arrayCity: allCity,
          arrayDotCity: dotCity,
          arrayDistrict: allDistrict,
          arrayDotDistrict: dotDistrict,
      })

          }
          /// 如果只是添加地址，set default
          if (option.justAdd === '1') {
             that.setData({
                arrayCity: ['北京'],
                arrayDotCity: ['北京'],
                arrayDistrict: ['东城区', '西城区', '崇文区', '宣武区', '朝阳区', '丰台区', '石景山区', '海淀区', '门头沟区', '房山区', '通州区', '顺义区', '昌平区', '大兴区', '怀柔区', '平谷区', '密云县', '延庆县'],
                arrayDotDistrict: ['东城区', '西城区', '崇文区', '宣武区', '朝阳区', '丰台区', '石景山区', '海淀区', '门头沟区', '房山区', '通州区', '顺义区', '昌平区', '大兴区', '怀柔区', '平谷区', '密云县', '延庆县'],
             })
          }
          that.setData({
              arrayProvince: allProvince,
              addressMain: res.data,
          })
      },
      fail: function(){
        // 如果本地没有存过地址信息，需要请求
          that.requestAddress(option);
      }
    })  
  },
  onShow: function(){
    // wx.showToast({
    //   title: '加载成功',
    //   icon: 'success',
    //   duration: 500
    // })
    // wx.hideToast()
  },
  
  // 提交信息
  submitAddress: function(e){
        // console.log('submitAddress', e.detail.value)
        let info = e.detail.value
        let that = this

        for(var prop in info){
            // 遍历信息，有空的就不能提交
            if(util.isEmpty(info[prop])){
                dialog.warn('信息填写不完整')
                return;
            }
        }

        // 要上传的address
        let address = {}
        // 如果改过了地址就用改过的
        if (this.data.isChangeCity) {
          address.province = this.data.arrayProvince[info.indexProvince]
          address.city = this.data.arrayCity[info.indexCity]
          address.suburb = this.data.arrayDistrict[info.indexDistrict]
        }else{
          // 没改过就用默认的
           address.province = this.data.province
           address.city = this.data.city
           address.suburb = this.data.suburb
        }
        address.receiver = info.receiverName
        address.phoneNo = info.receiverPhone
        address.postal = info.receiverYZ
        address.detail = info.detailAddr
        
        // 添加和编辑走不同的request
        if (that.data.justAdd) {
            req.addAddress(address, function(data){
                let addressId = data.returnData.addressId
                dialog.toast('添加成功')
                wx.navigateBack();

                wx.setStorage({
                  key: 'Address',
                  data: address,
                });
            },function(err){
                dialog.warn('添加失败，稍后重试')
            })
        }else{
            req.editAddress(that.data.addressId, address, function(){
                dialog.toast('修改成功')
                wx.navigateBack();
            }, function(){
                dialog.warn('修改失败，稍后重试')
            })
        }
        
    },
    /// 检查手机号
    checkPhone: function(data){
        let num=data.detail.value;
        if(util.checkPhoneFromString(num)){
            return;
        }else{
            dialog.warn('手机号有误')
        }
    },
    /// 检查邮政编码
    checkYZ: function(data){
        let YZNum=data.detail.value;
        if(YZNum.length===6){
            return;
        }else{
            dialog.warn('邮政号码有误')
        }
    },
    // 点击确定，选择了省会调用此方法
    // 确定了省，下一级市和下下级区也应该有所响应
  bindPickerChangeProvince: function(e) {
      // console.log(this.data.indexProvince)
      this.setData({
        isChangeCity: true,
      })
      var that = this
      let provinceIndex = e.detail.value // 会将index回传过来
      let allCity = []
      this.data.addressMain[provinceIndex].child.forEach(function(element){
          allCity.push(element.name)
      })
      let dotCity = that.addDot(allCity) // ...结尾的城市
      
      let allDistrict = []
      this.data.addressMain[provinceIndex].child[0].child.forEach(function(element){
          allDistrict.push(element.name)
      })
      let dotDistrict = that.addDot(allDistrict) // ...结尾的区

      this.setData({
          indexProvince: provinceIndex,
          arrayCity: allCity,
          arrayDotCity: dotCity,
          arrayDistrict: allDistrict,
          arrayDotDistrict: dotDistrict,
      })
  },
    // 点击确定，选择了市会调用此方法
    // 确定了市，下一级区应该有所响应
  bindPickerChangeCity: function(e) {
      this.setData({
        isChangeCity: true,
      })
      var that = this
      let cityIndex = e.detail.value
      let provinceIndex = this.data.indexProvince
      let allDistrict = []
      this.data.addressMain[provinceIndex].child[cityIndex].child.forEach(function(element){
          allDistrict.push(element.name)
      })
      let dotDistrict = that.addDot(allDistrict)
      
      this.setData({
          indexCity: cityIndex,
          arrayDistrict: allDistrict,
          arrayDotDistrict: dotDistrict,
      })
  },
  bindPickerChangeDistrict: function(e) {
      this.setData({
        isChangeCity: true,
      })
      this.setData({
          indexDistrict: e.detail.value
      })
  },
})